"""
Python多线程的实现案例
"""
import time
import _thread
import threading


def sing(name):
    for i in range(3):
        print("%s正在唱歌...%d" % (name, i))
        time.sleep(1)


def play(name):
    for i in range(3):
        print("%s正在玩游戏...%d" % (name, i))
        time.sleep(1)
    

def single_thread_demo():
	"""
	单线程案例
	"""
	name = 'hui'
	sing(name)
	play(name)


def fun_multithread():
	"""
	函数式使用多线程
	"""
	name = 'hui'

	# 启动唱歌、玩游戏线程
	sing_thread = _thread.start_new_thread(sing, (name, ))
	play_thread = _thread.start_new_thread(play, (name, ))


def thread_obj_demo():
	"""
	使用线程对象创建多线程
	"""
	name = 'hui'
	# 创建线程
	sing_thread = threading.Thread(target=sing, args=(name,))
	play_thread = threading.Thread(target=play, args=(name,))

	# 启动线程
	sing_thread.start()
	play_thread.start()


class MyThread(threading.Thread):
    
    # def __init__(self):
    #    super().__init__()
    
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字
            print(msg)


def custom_thread_demo():
	"""用户自定义线程类"""
	t1 = MyThread()
	t1.start()


def main():
	# single_thread_demo()

	# fun_multithread()
	# thread_obj_demo()

	# 防止主线程先执行完，导致子线程没有执行
	# time.sleep(3)

	custom_thread_demo()
	

if __name__ == '__main__':
	main()